import React, { useState, useEffect } from 'react';
import {
  Balloon,
  Button,
  Dialog,
  Form,
  Input,
  Icon,
  List,
  Loading,
  NumberPicker,
  Overlay,
  Radio,
  TreeSelect,
} from '@alifd/next';
import store from '@/store';
import styles from './index.module.scss';

const iconTypes = [
  'smile',
  'cry',
  'success',
  'warning',
  'prompt',
  'error',
  'help',
  'clock',
  'success-filling',
  'delete-filling',
  'favorites-filling',
  'add',
  'minus',
  'arrow-up',
  'arrow-down',
  'arrow-left',
  'arrow-right',
  'arrow-double-left',
  'arrow-double-right',
  'switch',
  'sorting',
  'descending',
  'ascending',
  'select',
  'semi-select',
  'loading',
  'search',
  'close',
  'ellipsis',
  'picture',
  'calendar',
  'ashbin',
  'upload',
  'download',
  'set',
  'edit',
  'refresh',
  'filter',
  'attachment',
  'account',
  'email',
  'atm',
  'copy',
  'exit',
  'eye',
  'eye-close',
  'toggle-left',
  'toggle-right',
  'lock',
  'unlock',
  'chart-pie',
  'chart-bar',
  'form',
  'language',
  'list',
  'dashboard',
];

const MainForm = (props) => {
  const { visible, handleVisible, menuId, refresh, mainField } = props;
  const [type, setType] = useState(0);
  const [iconVal, setIconVal] = useState('empty');
  const [loading, setLoading] = useState(false);
  const [menuState, menuDispatchers] = store.useModel('menu');
  const typeData = [
    { label: '目录', value: 0 },
    { label: '菜单', value: 1 },
    { label: '按钮', value: 2 },
  ];
  const typeObj = typeData.find((item) => {
    return item.value === type;
  });

  useEffect(() => {
    menuDispatchers.fetchTreeList();
  }, [menuDispatchers]);

  useEffect(() => {
    if (Object.keys(menuState.info).length > 0) {
      setType(menuState.info.type);
      setIconVal(menuState.info.icon === '' ? 'empty' : menuState.info.icon);
    }
  }, [menuState]);

  const treeList = [{ label: '一级菜单', value: '0', children: menuState.treeList }];

  const submitThen = () => {
    handleVisible(false);
    setLoading(false);
    setType(0);
    setIconVal('empty');
    refresh();
    menuDispatchers.fetchAsideNav();
  };
  const handleSubmit = async () => {
    setLoading(true);
    const { errors, values } = await mainField.validatePromise();
    if (errors === null) {
      if (menuId === 0) {
        menuDispatchers.saveInfo({ ...values, menuId }).then(submitThen);
      } else {
        menuDispatchers.updateInfo({ ...values, menuId }).then(submitThen);
      }
    }
  };

  const hiddenDialog = () => {
    handleVisible(false);
    setType(0);
    setIconVal('empty');
  };

  return (
    <>
      <Dialog
        title={menuId === 0 ? '新增' : '修改'}
        align="tc tc"
        minMargin={150}
        visible={visible}
        onOk={handleSubmit}
        onCancel={hiddenDialog}
        onClose={hiddenDialog}
        style={{ width: 600 }}
      >
        <Form field={mainField} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} useLabelForErrorMessage colon>
          <Form.Item label="类型">
            <Radio.Group
              dataSource={typeData}
              name="type"
              defaultValue={type}
              onChange={(value) => setType(value)}
              aria-labelledby="type"
            />
          </Form.Item>
          <Form.Item label={`${typeObj.label}名称`} required>
            <Input name="name" />
          </Form.Item>
          <Form.Item label="上级菜单">
            <TreeSelect dataSource={treeList} name="parentId" defaultValue="0" style={{ width: '100%' }} />
          </Form.Item>
          {type === 1 ? (
            <Form.Item label="菜单路由" required>
              <Input name="url" />
            </Form.Item>
          ) : null}
          {type !== 0 ? (
            <Form.Item label="授权标识">
              <Input name="perms" placeholder="多个用逗号分隔, 如: user:list,user:create" />
            </Form.Item>
          ) : null}
          {type !== 2 ? (
            <Form.Item label="排序">
              <NumberPicker name="orderNum" defaultValue={0} min={0} />
            </Form.Item>
          ) : null}
          <Form.Item label="图标">
            <Input name="icon" value={iconVal === 'empty' ? '' : iconVal} htmlType="hidden" />
            <Overlay.Popup
              trigger={
                <Input
                  className={styles.icon_input}
                  addonTextBefore={<Icon type={iconVal} />}
                  addonAfter={<Button onClick={() => setIconVal('empty')}>清除</Button>}
                  value={iconVal === 'empty' ? '' : iconVal}
                />
              }
              triggerType="click"
              className={styles.icon_overlay}
            >
              <div>
                <List
                  divider={false}
                  dataSource={iconTypes}
                  renderItem={(item, i) => (
                    <Balloon.Tooltip
                      key={i}
                      align="t"
                      trigger={
                        <List.Item onClick={() => setIconVal(item)}>
                          <Icon type={item} />
                        </List.Item>
                      }
                    >
                      {item}
                    </Balloon.Tooltip>
                  )}
                />
              </div>
            </Overlay.Popup>
          </Form.Item>
        </Form>
        <Loading className={styles.loading} visible={loading} />
      </Dialog>
    </>
  );
};

export default MainForm;
